<!-- 左侧导航栏 -->
<template>
  <nav class="left-navbar">
    <!-- Logo区域 -->
    <div class="navbar-brand">
      <router-link to="/" class="brand-link">
        <logo />
      </router-link>
    </div>

    <div class="flex justify-center">
      <svg width="137" height="1" viewBox="0 0 137 1" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M0.25 0.25H136.25" stroke="#E1E2E3" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </div>

    <!-- 导航菜单 -->
    <div class="navbar-menu">
      <div class="menu-list">
        <div v-for="item in navItems" :id="item.name" :key="item.path" >
          <div class="flex justify-center" v-if="item.type === 'line'">
            <svg width="137" height="1" viewBox="0 0 137 1" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M0.25 0.25H136.25" stroke="#E1E2E3" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <div v-else class="menu-item" @click="handleMenuClick(item.path)" >
            <router-link  :to="item.path" class="menu-link" :class="{ 'active': isActiveRoute(item.path) && !showNotificationSidebar  }">
            <component :is="getIconComponent(item.iconComponent)" :size="16"
              :color="isActiveRoute(item.path) && !showNotificationSidebar ? '#F76B1B' : '#222222'" />
            <span>{{ item.name }}</span>
             <IconAiPointer class="icon-ai-pointer" v-if="item.path === '/generator'"/>
          </router-link>
          </div>
          
        </div>
      </div>
    </div>

    <!-- 底部操作区域 -->
    <div>
      <div v-if="userInfo" class="mb-[24px] px-[8px]">
        <!-- 消息通知 -->
        <div class="menu-link mb-[8px]" @click="toggleNotificationSidebar" :class="{active: showNotificationSidebar}">
          <div class="relative">
            <component :is="getIconComponent('IconNotice')" :size="16" :color="showNotificationSidebar ? '#F76B1B' : '#222222'"/>
            <!-- 未读消息红点 -->
            <div v-if="hasNewMessage" class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"></div>
          </div>
          <span class="text-[15px] font-[500] text-[#222222]">Notification</span>
        </div>
        <!-- 用户信息 -->
        <el-popover placement="right" :width="160" popper-style="border-radius: 8px; padding: 8px;transform: translateY(-24%);" :show-arrow="false" :offset="16" trigger="hover">
           <template #reference>
             <div class="flex items-center h-[40px] gap-[8px] px-[12px] cursor-pointer  rounded-[8px] hover:bg-[#EDEDED]" :class="{'user-active': isActiveUserRoute}">
                <img :src="userInfo?.avatar" class="w-[32px] h-[32px] cursor-pointe rounded-full flex-shrink-0" alt=""
                ></img>
                <span class="text-[15px] font-[500] overflow-hidden text-ellipsis whitespace-nowrap">{{ userInfo?.name }}</span>
              </div>
           </template>
            <div class="flex flex-col text-[14px] text-[#7A7A7A] w-full">
              <div class="cursor-pointer p-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]" v-for="(item,index) in userTabList" :key="index" @click="gotoPage(item.path)">
                <span >{{ item.name }}</span>
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none">
                  <path fill-rule="evenodd" clip-rule="evenodd" d="M9.10983 3.48483C9.25628 3.33839 9.49372 3.33839 9.64017 3.48483L11.1402 4.98484C11.2866 5.13128 11.2866 5.36872 11.1402 5.51516L9.64017 7.01516C9.49372 7.16161 9.25628 7.16161 9.10983 7.01516C8.96339 6.86872 8.96339 6.63128 9.10983 6.48484L9.96967 5.625H3.60938C2.44854 5.625 1.5 6.60391 1.5 7.78125V8.25C1.5 8.45711 1.33211 8.625 1.125 8.625C0.917893 8.625 0.75 8.45711 0.75 8.25V7.78125C0.75 6.20844 2.01583 4.875 3.60938 4.875H9.96967L9.10983 4.01517C8.96339 3.86872 8.96339 3.63128 9.10983 3.48483Z" fill="#CBCBCB"/>
                </svg>
              </div>

              <!-- 分割线 -->
              <div class="py-[8px] box-content">
                <svg xmlns="http://www.w3.org/2000/svg" width="186" height="2" viewBox="0 0 186 2" fill="none" class="w-full">
                  <path d="M1 1H185" stroke="#EDEDED" stroke-linecap="round"/>
                  </svg>
              </div>

              <!-- 退出登录 -->
              <div class="cursor-pointer p-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]" @click="showLogout=true">
                Log Out
              </div>

            </div>
         </el-popover>
        
      </div>
      <div v-else class="mb-[24px] px-[16px]">
        <div class="text-[15px] font-[500] py-[12px]  text-center bg-[#EDEDED] rounded-[42px] cursor-pointer hover:bg-[#E1E2E3]"
          @click="handleGetStarted">
          Log in / Sign up
        </div>
      </div>

      <!-- 平台 -->
      <div class="flex items-center   bottom_platform">
        <div class="py-[16px] flex gap-[16px] px-[24px] items-center">
          <component :is="getIconComponent('IconX')" class="cursor-pointer" @click="toPage('https://x.com/nexbieofficial?s=21')" />
          <component :is="getIconComponent('IconIg')" class="cursor-pointer" @click="toPage(' https://www.instagram.com/nexbieofficial')" />
          <component :is="getIconComponent('IconTK')" class="cursor-pointer" @click="toPage('https://www.tiktok.com/@nexbieofficial')" />
        </div>

        <div class="flex-1 flex justify-center bottom_left py-[16px]">
          <el-popover placement="top" :width="200" popper-style="border-radius: 8px; padding: 8px; transform: translateX(-14%);box-sizing: content-box;" trigger="click"  :show-arrow="false" :offset="24">
            <template #reference>
              <component :is="getIconComponent('IconSpread')" class="cursor-pointer outline-none" />
            </template>
            <div class="flex flex-col text-[14px] text-[#7A7A7A] w-full">
              <div @click="goPage('/guidelines')" class="cursor-pointer p-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px] group">
                <span>Nexbie Guidelines</span>
                <ArrowRight class="group-hover:text-[#222]"/>
              </div>
              <div @click="goPage('/aboutUS')" class="cursor-pointer p-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px] group">
                <span>About Nexbie</span>
                 <ArrowRight class="group-hover:text-[#222]"/>
              </div>

              <div class="group cursor-pointer p-[8px] mb-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]" @click="gotoPage('https://docs.google.com/forms/d/e/1FAIpQLSemSjU6uoZYomzizkItwhtkBE-ePyQlDotYzFmoHKkVB4-z9Q/viewform?usp=publish-editor')">
                <span>Feedback</span>
                <ArrowRight class="group-hover:text-[#222]"/>
              </div>

              <svg xmlns="http://www.w3.org/2000/svg" width="185" height="1" viewBox="0 0 185 1" fill="none" class="w-full">
  <path d="M0.5 0.5H184.5" stroke="#EDEDED" stroke-linecap="round"/>
</svg>


              <div @click="goPage('/terms')" class="group cursor-pointer p-[8px] mt-[8px] flex items-center justify-between hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]">
                <span>Terms and Conditions</span>
                  <ArrowRight class="group-hover:text-[#222]"/>
              </div>
              <el-popover placement="right" :width="160" popper-style="border-radius: 8px; box-sizing: content-box;" :offset="13" :show-arrow="false" >
                <template #reference>
                  <div class="group cursor-pointer p-[8px] hover:text-[#222] hover:bg-[#F8F8F8] flex items-center justify-between hover:rounded-[4px]">
                    <span>Privacy</span>
                    <ArrowRightIn class="group-hover:text-[#222]"/>
                  </div>
                </template>

                <div class="flex flex-col text-[14px] text-[#7A7A7A] w-full">
                  <div @click="goPage('/privacy')"  class="group flex justify-between items-center cursor-pointer p-[8px] hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]">
                    Privacy 
                     <ArrowRight class="group-hover:text-[#222]"/>
                  </div>
                  <div @click="goPage('/cookiePolicy')"  class="group flex justify-between items-center cursor-pointer p-[8px] hover:text-[#222] hover:bg-[#F8F8F8] hover:rounded-[4px]">
                    Cookie 
                     <ArrowRight class="group-hover:text-[#222]"/>
                  </div>
                </div>

                </el-popover>
              
              <div class="py-[8px] box-content">
         
              <svg xmlns="http://www.w3.org/2000/svg" width="185" height="1" viewBox="0 0 185 1" fill="none" class="w-full">
  <path d="M0.5 0.5H184.5" stroke="#EDEDED" stroke-linecap="round"/>
</svg>
              </div>
             
              <div class=" text-[12px]">© 2025 Nexbie</div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>
  </nav>

  <!-- 消息侧边栏组件 -->
  <NotificationSidebar 
    :show="showNotificationSidebar" 
    :InteractionsCount="InteractionsCount"
    :OfficialCount="OfficialCount"
    @close="closeNotificationSidebar"
     />

   <!-- 退出登录弹窗 -->
   <div v-if="showLogout" class="modal-overlay" @click="cancelLogout">
     <div class="logout-modal" @click.stop>
       <div class="logout-content">
         <div class="logout-title">Confirm Log Out?</div>
         <!-- <div class="logout-message">Are you sure you want to log out?</div> -->
       </div>
       <div class="logout-content-footer">
         <div class="logout-content-footer-button cancel-button" @click="cancelLogout">
           <span>No</span>
         </div>
         <div class="logout-content-footer-button confirm-button" @click="handleLogout">
           <span>Log Out</span>
         </div>
       </div>
     </div>
   </div>


  <NewUserModal />
  <Overlay :visible="newUserGuideStep === 3">
    <div class="modal_guide relative" :style="{marginTop:userGuideModeHeight + 4  + 'px'}">
      <img class="step2_img ml-[8px]" src="https://imgs.nexbie.com/uploads/67367e9cd0d54d75912113739d2a3fd1.webp" alt="">
      <UserGuideStep class="step2_view" />
    </div>
  </Overlay>

</template>

<script setup lang="ts">
import {computed, ref, onMounted, onUnmounted, nextTick} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Logo from '@/components/icons/logo.vue'
import * as MenuIcons from '@/components/icons/menu/index';
import { useUserStore, } from '@/store/user'
import { UserAPI } from '@/api/user';
import NotificationSidebar from './NotificationSidebar.vue';
import IconAiPointer from '@/components/icons/menu/IconAiPointer.vue'
import Overlay from '@/components/Overlay.vue'
import NewUserModal from '@/components/NewUserModal.vue'
import { getElementInfoById } from '@/utils/guideTools'
import UserGuideStep from '@/components/UserGuideStep.vue'
import ArrowRight from '@/components/icons/home/ArrowRight.vue'
import ArrowRightIn from '@/components/icons/home/ArrowRightIn.vue'



const userStore = useUserStore();

// 响应式数据
const route = useRoute()
const router = useRouter()
const showLogout = ref(false)

// 消息侧边栏状态
const showNotificationSidebar = ref(false)

// 消息状态轮询
const hasNewMessage = ref(false)
const pollingTimer = ref<NodeJS.Timeout | null>(null)
const userGuideModeHeight = ref<number>(0)

const newUserGuideStep = computed(() => userStore.newUserGuideStep);
console.log('newUserGuideStep',newUserGuideStep.value)
const userInfo = computed(() => userStore.user);

// 导航菜单项
const navItems = ref<any[]>([
  {
    name: 'Home',
    path: '/',
    iconComponent: 'IconHome'
  },
  // {
  //   name: 'Nex Group',
  //   path: '/group',
  //   iconComponent: 'IconGroup'
  // },
  {
    name: 'Designer',
    path: '/designer',
    iconComponent: 'IconDesigner'
  },
  {
    name: 'Product',
    path: '/product',
    iconComponent: 'IconProduct'
  },
  {
    type: 'line',
  },
  {
    name: 'Contest',
    path: '/contest',
    iconComponent: 'IconContest',
    slug: true
  },
    {
    type: 'line',
  },
  {
    name: 'Nex Lab',
    path: '/generator',
    iconComponent: 'IconLab'
  }
])

// 用户菜单
const userTabList = ref([
  {
    name: 'Profile',
    path: '/profile'
  },
  {
    name: 'Orders',
    path: '/orders'
  },  
  {
    name: 'Settings',
    path: '/settings'
  }
])

const goPage = (path:string) => {
  router.push(path)
}

const toPage = (url:string) => {
  window.open(url, '_blank')
}

const isActiveUserRoute = computed(() => {
  return userTabList.value.some(item => item.path === route.path) && !showNotificationSidebar.value
})

// 获取图标组件
const getIconComponent = (iconComponentName: string) => {
  return MenuIcons[iconComponentName as keyof typeof MenuIcons] || null;
};

// 计算属性
const isActiveRoute = (path: string) => {
  return route.path === path
}

// 展示新手引导
const showNewUserGuide = () => {
  const el:any = getElementInfoById('Contest')
  userGuideModeHeight.value = el.top
}



const handleLogout =async () => {
  console.log('退出登录')
  await UserAPI.logout();
  userStore.logout()
  showLogout.value = false
  router.push('/')
}

// 取消退出登录
const cancelLogout = () => {
  showLogout.value = false
}


// 处理Get Started按钮点击
const handleGetStarted = () => {
  router.push('/login')
}

// 跳转到某个页面
const gotoPage = (path: string) => {
  // 判断是否是外部链接（http:// 或 https://）
  closeNotificationSidebar()
  if (path.startsWith('http://') || path.startsWith('https://')) {
    // 在新窗口打开外部链接
    window.open(path, '_blank')
  } else {
    // 路由跳转
    router.push(path)
  }
  closeNotificationSidebar()
}


const handleMenuClick = (path: string) => {
  console.log('菜单项被点击')
  router.push(path)
  closeNotificationSidebar()
}

// 消息侧边栏方法
const toggleNotificationSidebar = () => {
  showNotificationSidebar.value = !showNotificationSidebar.value
}

const closeNotificationSidebar = () => {
  showNotificationSidebar.value = false
}



const InteractionsCount = ref(0)
const OfficialCount = ref(0)
// 检查消息状态
const checkMessageStatus = async () => {
  if(!userInfo.value) return
  try {
    const response = await UserAPI.hasMessage()
    
    // 根据API返回的数据结构更新状态
    if (response.code == 200) { 
      InteractionsCount.value = response.data.unread_like_count + response.data.unread_comment_count + response.data.unread_follow_count
      OfficialCount.value = response.data.unread_sys_msg_count
      hasNewMessage.value = InteractionsCount.value || response.data.unread_sys_msg_count || false
    }
  } catch (error) {
    console.error('检查消息状态失败:', error)
  }
}

// 开始轮询
const startPolling = () => {
 // TODO
 //  return
  // 先立即检查一次
  checkMessageStatus()
  
  // 设置定时器每500ms检查一次
  pollingTimer.value = setInterval(() => {
    checkMessageStatus()
  }, 5*60*1000)
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

// 生命周期
onMounted(() => {
  // 启动消息状态轮询
  startPolling()
  nextTick(showNewUserGuide)
})

onUnmounted(() => {
  // 组件销毁时停止轮询
  stopPolling()
})

</script>

<style lang="scss" scoped>
.left-navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 184px;
  height: 100vh;
  background: #ffffff;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  z-index: 1000;
}

.modal_guide {
  display: flex;
  flex-direction: row;
  .step2_img {
    width: 168px;
    height: 48px;
  }

  .modal_left {
    background: #fff;
    border-radius: 4px;
    margin-left: 6px;
    max-height: 48px;
  }
}

.navbar-brand {
  padding: 24px 20px;
  // border-bottom: 1px solid #e5e7eb;

  .brand-link {
    display: flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    color: #222;
    font-weight: 600;
    font-size: 16px;
  }
}

.navbar-menu {
  flex: 1;
}

.menu-list {
  list-style: none;
  margin: 0;
  padding: 8px 10px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.menu-item {
  // margin-bottom: 8px;
  // &:last-child {
  //   margin-bottom: 0;
  // }
  // &.slug {
  //   border-top: 0.5px solid #E1E2E3;
  //   border-bottom: 0.5px solid #E1E2E3;
  //   padding: 8px 0px;
  // }
}

.pl_pr {
  padding: 14px 18px 14px 2px!important;
  margin-left: 8px;
}


.menu-link {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  white-space: nowrap;
  text-decoration: none;
  color: #222222;
  font-size: 15px;
  transition: all 0.2s ease;
  border-radius: 0;
  height: 40px;
  border-radius: 8px;
  cursor: pointer;
  &:hover {
    font-weight: 500;
    color: #222;
     background: #F8F8F8;
  }
  
  &.active {
    background-color: #FBE6DB;
    color: #F76B1B;
    font-weight: 500;
  }

  span {
    color: inherit;
    font-size: 15px;
    font-style: normal;
    font-weight: 500;
    line-height: normal;
  }
}

.user-active {
   background-color: #FBE6DB;
    color: #F76B1B;
    font-weight: 500;
}

// 退出登录弹窗样式
.logout-modal {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  width: 480px;
  height: 160px;
  animation: slideIn 0.3s ease;
}

.logout-content {

  padding: 24px 24px 16px 24px;
  text-align: center;
}

.logout-title {
  font-size: 20px;
  font-weight: 500;
  color: #222;
  margin-bottom: 8px;
}

.logout-message {
  font-size: 14px;
  color: #7A7A7A;
  line-height: 1.5;
}

.logout-content-footer {
  display: flex;
  gap: 12px;
  padding: 16px 24px 24px 24px;
}

.logout-content-footer-button {
  flex: 1;
  padding: 12px 24px;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
  font-size: 18px;

  &.cancel-button {
    background: var(---2, #EDEDED);
    backdrop-filter: blur(2px);
    color: #222;

    &:hover {
      background: #E1E2E3;
      color: #222;
    }
  }

  &.confirm-button {
    color: white;
    background: var(---, linear-gradient(90deg, #F76B1B 0%, #DC3A0E 100%));
    backdrop-filter: blur(2px);
    &:hover {
      background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.bottom_platform {
  border-top: 0.5px solid #E1E2E3;
}

.bottom_left {
  border-left: 0.5px solid #E1E2E3;
}

.icon-ai-pointer {
  position: relative;
  left: -10px;
  top: -10px;
}

.step2_view {
  position: absolute;
  left: 200px;
  top:-35px
}

</style>
